<template>
    <el-container>
      <el-header>
        <el-button type="primary" @click="getAppointmentList">获取预约列表</el-button>
      </el-header>
      <el-main>
        <el-table :data="appointmentList" style="width: 100%">
          <el-table-column prop="appointmentTime" label="预约时间" />
          <el-table-column prop="patientName" label="患者姓名" />
          <el-table-column prop="doctorName" label="医生姓名" />
          <el-table-column prop="clinicName" label="科室名称" />
          <el-table-column prop="status" label="状态" width="180">
            <template #default="scope">
              <span
                style="cursor: pointer; color: #409eff"
                @click="handleStatusClick(scope.row)"
              >
                {{ scope.row.status }}
              </span>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 付款码弹窗 -->
        <el-dialog v-model="dialogVisible" title="付款码" width="30%">
          <div style="text-align: center">
            <img :src="paymentCodeImageUrl" width="400" height="400" alt="付款码" />
          </div>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handlePaymentSuccess">支付成功</el-button>
            </span>
          </template>
        </el-dialog>
      </el-main>
    </el-container>
    <div ref="paymentContainer" v-html="paymentForm"></div>
  </template>
  
  <script setup>
  import { ref, nextTick } from 'vue';
  import { ElMessage } from 'element-plus';
  import { getAppointmentByPatientId, updateAppointment } from '@/api/appointment';
  import { getAllPatientsService } from '@/api/admin.js';
  import { useUserInfoStore } from '@/stores/userInfo.js';
  import { userInfoGetService } from '@/api/user.js';
  import { alipay } from '@/api/appointment'
  // 初始化数据
  const userInfoStore = useUserInfoStore();
  const appointmentList = ref([]);
  const dialogVisible = ref(false); // 控制付款码弹窗显示
  const dialogAppointmentId = ref(null); // 记录当前点击的预约 ID
  const paymentCodeImageUrl = ref(''); // 示例付款码图片地址
  const paymentCode = ref({
    out_trade_no: '',
      subject: '',
      total_amount: '',
      body: '',
      paymentForm: ''
  });
  const paymentForm = ref(''); // 定义 paymentForm 变量
  const paymentContainer = ref(null); // 定义 paymentContainer 变量

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const result = await userInfoGetService();
      userInfoStore.setInfo(result.data);
    } catch (error) {
      ElMessage.error('获取用户信息失败，请重试');
    }
  };
  
  // 获取患者ID
  const getAllPatients = async () => {
    try {
      const result = await getAllPatientsService();
      for (const patient of result.data) {
        if (patient.username === userInfoStore.info.username) {
          appointmentList.value.patientId = patient.patientId;
          return; // 找到后直接退出循环
        }
      }
    } catch (error) {
      ElMessage.error('获取患者信息失败，请重试');
    }
  };
  
  // 获取预约列表
  const getAppointmentList = () => {
    if (!appointmentList.value.patientId) {
      ElMessage.warning('尚未获取患者信息，请稍后再试');
      return;
    }
    getAppointmentByPatientId(appointmentList.value.patientId)
      .then((res) => {
        appointmentList.value = res.data;
      })
      .catch((error) => {
        ElMessage.error('获取预约信息失败，请重试');
      });
  };
  
  // 处理状态点击事件
  const handleStatusClick = (row) => {
    switch (row.status) {
      case '待支付':
        dialogVisible.value = true;
        paymentCode.value.out_trade_no = row.appointmentId;
        paymentCode.value.subject = '预约挂号';
        paymentCode.value.total_amount = 10;
        paymentCode.value.body = '预约挂号';
        alipay(paymentCode.value).then(res => {
        if (res.code === 0) {
          paymentForm.value = res.data;
          nextTick(() => {
            const form = paymentContainer.value.querySelector('form');
            if (form) {
              form.submit();
            }
          });
        } else {
          console.error('支付失败:', res.message);
        }
      }).catch(error => {
        console.error('请求错误:', error);
      });
        dialogAppointmentId.value = row.appointmentId;
        break;
      case '已过期':
        ElMessage.warning('该预约已过期');
        break;
      case '已支付':
        // 申请退款并将状态改为'已取消'
        updateAppointment({ appointmentId: row.appointmentId, status: '已取消' }).then(() => {
          // 提示成功
          ElMessage.success('退款成功，状态已更新');
          // 重新获取预约列表以反映最新的状态
          getAppointmentList();
        }).catch((error) => {
          ElMessage.error('退款失败，请重试');
        });
        break;
      default:
        ElMessage.info('当前状态无法操作');
        break;
    }
  };
  
  // 处理支付成功
  const handlePaymentSuccess = () => {
    // 调用后端接口更新状态
    updateAppointment({ appointmentId: dialogAppointmentId.value, status: '已支付' }).then(() => {
      // 关闭弹窗
      dialogVisible.value = false;
      // 提示成功
      ElMessage.success('支付成功，状态已更新');
      // 重新获取预约列表以反映最新的状态
      getAppointmentList();
    }).catch((error) => {
      ElMessage.error('支付失败，请重试');
    });
  };
  
  // 初始化数据
  getUserInfo();
  getAllPatients();
  getAppointmentList();
  </script>
  
  <style scoped>
  /* 添加一些样式让界面更美观 */
  .el-header {
    padding: 10px 20px;
    background-color: #f5f5f5;
    line-height: 60px;
  }
  
  .el-main {
    padding: 20px;
  }
  
  .el-table {
    margin-top: 20px;
  }
  </style>